from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
# Create your views here.

from .readnovel_class import *
import json

def readapi_search(request):
    if request.method == 'POST': 
        search_info = request.POST
        keyword = search_info['keyword']
        novel_obj = ReadNovelClass(keyword = keyword)
        last_info = novel_obj.search_info()
        
        return HttpResponse(json.dumps(last_info))
    if request.method == 'GET':
        return HttpResponse('请使用POST方式请求search接口！')

def readapi_homepage(request):
    if request.method == 'POST':
        home_info = request.POST
        home_para = home_info['home_page']
        if home_para == 'homepage':
            free_url = 'https://www.readnovel.com/free/all?pageSize=10&gender=2&catId=-1&isFinish=-1&isVip=1&size=-1&updT=-1&orderBy=0&pageNum={}'.format(1)
            home_obj = ReadNovelClass(free_url = free_url)
            last_info = home_obj.free_novel()
            print(last_info)
            return HttpResponse(json.dumps(last_info))
        else:

            return HttpResponse('参数不对！')
    if request.method == 'GET':
        return HttpResponse('请使用POST方式请求homepage接口！')

def readapi_novel_info(request):
    if request.method == 'POST':
        novel_info = request.POST
        novel_main_url = 'https://www.readnovel.com/book/'
        novel_message = novel_info['novel_url']
        novel_message = novel_message.split('/')[-1]
        novel_last_url = novel_main_url + novel_message
        novel_obj = ReadNovelClass(book_url = novel_last_url)
        novel_detail_info = novel_obj.book_info()
        novel_chapter_info = novel_obj.chapter_info()
        novel_detail_info['novel_chapter_info'] = novel_chapter_info
        print(novel_detail_info)
        return HttpResponse(json.dumps(novel_detail_info))
    if request.method == 'GET':
        return HttpResponse('请使用POST方式请求novel_info接口！')

def readapi_chapter_info(request):
    if request.method == 'POST':
        chapter_info = request.POST
        chapter_main_url = 'https://www.readnovel.com/chapter/'
        chapter_message = chapter_info['chapter_url']
        chapter_message1 = chapter_message.split('/')[-2]
        chapter_message2 = chapter_message.split('/')[-1]
        print(chapter_message)
        chapter_last_url = chapter_main_url + chapter_message1 + '/' + chapter_message2
        print(chapter_last_url)
        chapter_obj = ReadNovelClass(chapter_url = chapter_last_url)
        chapter_info_dict = chapter_obj.detail_info()
        return HttpResponse(json.dumps(chapter_info_dict))
